import {
  Home2
} from 'index-model.js';
var home = new Home2(); //实例化 首页 对象
import {
  Config
} from '../../utils/config.js';
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
import {
  User
} from '../../model/user-model.js';

var user = new User();

import {
  Job
} from '../../model/job-model.js';
var job = new Job();
import {
  Token
} from '../../utils/token.js';

var token = new Token();

import {
  Company
} from '../../model/company-model.js';
var company = new Company();

import {
  Note
} from '../findworker/note-model.js';
var note = new Note();
Page({
  data: {
    url_route: '',
    autoplay: true,
    interval: 3000,
    duration: 1000,

    interval2: 3500,
    duration2: 2000,
    //是否采用衔接滑动
    circular: true,
    //是否显示画板指示点
    indicatorDots: false,
    //选中点的颜色
    indicatorcolor: "#000",
    //是否竖直
    vertical: false,
    //是否自动切换
    //滑动动画时长毫秒
    //所有图片的高度
    imgheights: [],
    //图片宽度
    imgwidth: 750,
    //默认
    current: 0,
    swiperCurrent: 0,
    loadingHidden: false,
    title: '',
    ischeck: 0
  },
  onReady() {},

  initObserver() {
    if (this.observer) {
      this.observer.disconnect();
    }
    this.observer = this.createIntersectionObserver({
      thresholds: [0],
      initialRatio: 0,
    });
    this.observer.relativeToViewport({
      top: 0
    }).observe('#triggerView', (res) => {
      if (res.intersectionRatio === 0) {
        this.setData({
          showHeader: true
        });
      } else {
        console.log("showHeader: false")
        this.setData({
          showHeader: false
        });
      }
    });
  },
  imageLoad: function (e) {
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比
      ratio = imgwidth / imgheight;
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight
    var imgheights = this.data.imgheights
    //把每一张图片的高度记录到数组里
    imgheights.push(imgheight)
    this.setData({
      imgheights: imgheights,
    })
  },
  bindchange: function (e) {
    console.log(e.detail.current)
    this.setData({
      current: e.detail.current
    })
  },

  swiperChange: function (e) {

    this.setData({
      swiperCurrent: e.detail.current //获取当前轮播图片的下标
    })
  },


  onShow: function () {

    var that = this;


    var cityinfo = wx.getStorageSync('cityinfo');

    if (cityinfo) {

      wx.setStorageSync('city', cityinfo.name);

      that._loadData();

    } else {

      //获取信息
      qqmapsdk = new QQMapWX({
        key: '5D3BZ-J55WF-SFPJJ-NI6PG-YN2ZO-M4BHX' // 必填
      });
      wx.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
        success: function (res) {
          wx.setStorageSync('latitude', res.latitude);
          wx.setStorageSync('longitude', res.longitude);
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function (addressRes) {

              var address = addressRes.result.address_component.city;

              var city = address.substr(0, address.length - 1);

              console.log(city);

              wx.setStorageSync('city', city);

              that._loadData();

            }
          })




        },
        fail: function () {
          // fail

          that._loadData();
        },
        complete: function () {
          // complete
        }
      })



    }
    wx.nextTick(() => {
      // 等待当前一轮视图更新完成后再创建观察器
      this.initObserver();
    });
  },
  onHide() {
    if (this.observer) {
      this.observer.disconnect();
    }
  },

  onUnload() {
    if (this.observer) {
      this.observer.disconnect();
    }
  },

  selectjobtype: function (e) {
    var that = this;
    var worktype = e.currentTarget.dataset.id;
    that.data.worktype = worktype;
    that.setData({
      worktype: that.data.worktype
    })

    that.getjoblist();



  },


  getjoblist: function () {
    var that = this;
    var cityid = wx.getStorageSync('cityinfo').id;
    var params = {
      cityid: cityid,
      worktype: that.data.worktype
    };

    job.getJobIndexList((data) => {


      that.setData({
        joblist: data.joblist
      });
    }, params);


  },



  onLoad: function (options) {
    var that = this;
    that.setData({
      url_route:that.route,// 当前页面路径
    });
    // wx.setStorageSync('rectid',10);
    if (options) {
      if (options.hasOwnProperty("scene")) {
        var scene = decodeURIComponent(options.scene);
        var uid_array = scene.split('=');
        if (uid_array[0] == 'rectid') {
          var rectid = parseInt(uid_array[1]);
          wx.setStorageSync('rectid', rectid);

        } else {

          var uid = parseInt(uid_array[1]);
          wx.setStorageSync('tid', uid);
        }
      }
    }


    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    //  var cityinfo =[];
    //cityinfo.name = '盐城';
    //wx.setStorageSync('cityinfo',cityinfo);



  },


  rectbinduser: function () {

    if (wx.getStorageSync('rectid') > 0) {

      var params = {
        rectid: wx.getStorageSync('rectid')
      };


      home.rectBinduser((data) => {

      }, params);

    }

  },


  fxbinduser: function () {

    if (wx.getStorageSync('tid') > 0) {


      var params = {
        tid: wx.getStorageSync('tid')
      };

      home.fxBinduser((data) => {

      }, params);

    }

  },

  /*加载所有数据*/
  _loadData: function (callback) {
    var that = this;
    var city;
    city = wx.getStorageSync('city');
    home.getSysinit(city, (data) => {

      if (data.sysinfo) {
        wx.setNavigationBarTitle({
          title: data.sysinfo.name,
        })

        that.data.title = data.sysinfo.name;
        that.data.ischeck = data.sysinfo.ischeck;

      }

      wx.setStorageSync('cityinfo', data.cityinfo);

      var worktypelist = data.worktyelist;
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect()

      if (worktypelist.length > 0)
        that.data.worktype = worktypelist[0]['id'];
      that.setData({
        ischeck: that.data.ischeck,
        oldhouselist: data.oldhouselist,
        worktype: that.data.worktype,
        city: wx.getStorageSync('cityinfo').name,
        bannerlist: data.bannerlist,
        navlist: data.navlist,
		workCrowd: data.workCrowd,
        companylist: data.companylist,
        worktyelist: data.worktyelist,
        sysinfo: data.sysinfo,
        capsuleTop: menuButtonInfo.top,
        capsuleHeight: menuButtonInfo.height,
        showHeader: true,
        currentPage: 0,
        noticelist: data.noticelist
      });


      that.getjoblist();
      var latitude = wx.getStorageSync('latitude');
      var longitude = wx.getStorageSync('longitude');
      home.showArea({
        cityid: wx.getStorageSync('cityinfo').id,
        lng: longitude,
        lat: latitude
      }, (data) => {
        console.log(data)
        var quickNavlist = data.data.map(item => ({
          ...item,
          fullImage: this.getImageUrl(item.image)
        }));
        that.setPagedList(quickNavlist)
        this.checkTriggerVisibility();
        this.updateProgress(0, this.data.pagedList.length)
      })

      if (wx.getStorageSync('tid') > 0) {

        setTimeout(() => {

          that.fxbinduser();

        }, 2000)

      }

      if (wx.getStorageSync('rectid') > 0) {

        that.rectbinduser();
      }


      wx.hideNavigationBarLoading(); //完成停止加载
      wx.stopPullDownRefresh();
    });


  },

  setPagedList(list) {
    const pageSize = 5;
    const paged = [];

    for (let i = 0; i < list.length; i += pageSize) {
      paged.push(list.slice(i, i + pageSize));
    }
    console.log(paged)
    this.setData({
      pagedList: paged,
    });
  },
  updateProgress(current, total) {
    const percent = ((current + 1) / total) * 100
    this.setData({
      progressPercent: percent
    })
  },

  getImageUrl(url) {
    return Config.imageUrlS + url
  },
  onSwiperChange(e) {
    const current = e.detail.current
    const total = this.data.pagedList.length
    this.setData({
      currentPage: current
    })
    this.updateProgress(current, total)
  },
  toNagivate: function (e) {
    var url = e.currentTarget.dataset.id;
    console.log(url);
    wx.navigateTo({
      url: url
    })
  },

  toSwitchtab: function (e) {
    var url = e.currentTarget.dataset.id;
    wx.switchTab({
      url: url
    })
  },

  toWorkCrowd() {
    wx.navigateTo({
      url: '/pages/workCrowd/index',
    })
  },
  toWxapp: function (e) {
    var url = e.detail.value.innerurl;
    var appid = e.detail.value.appid;
    console.log(url);
    console.log(appid);
    wx.navigateToMiniProgram({
      appId: appid,
      path: url,
      extraData: {
        foo: 'bar'
      },
      envVersion: 'develop',
      success(res) {
        // 打开成功
      }
    })
  },

  toInnerUrl: function (e) {

    console.log(e)
    var url = e.detail.value.innerurl;
    wx.navigateTo({
      url: url
    })

  },

  handleClick(e) {
    const {
      id,
      name
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: "/pages/findjob/index?areaid=" + id
    });
  },

  toPicInnerUrl: function (e) {


    var url = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: url
    })

  },

  toWebview: function (e) {


    var id = e.detail.value.id;
    var url = "/pages/webview/index?id=" + id;
    wx.navigateTo({
      url: url
    })

  },

  toMenuUrl: function (e) {

    var url = e.detail.value.innerurl;
    wx.switchTab({
      url: url
    })

  },

  toCompanylist: function () {

    var that = this;

    wx.navigateTo({
      url: "/pages/companylist/index"
    })

  },
  toSelectJob: function () {

    var that = this;

    wx.navigateTo({
      url: "/pages/selectjob/index"
    })

  },

  toPerLogin: function () {

    var that = this;

    wx.navigateTo({
      url: "/pages/login/index"
    })


  },

  toPerRegister: function () {

    var that = this;

    wx.navigateTo({
      url: "/pages/register/index"
    })


  },

  toTaskjob: function () {
    wx.redirectTo({
      url: '/pages/findjob/index'
    })
    // var that = this;
    //
    // var params = {};
    //
    // token.verify(
    //
    //   user.checkBind((data) => {
    //
    //     if (data.isbind) {
    //
    //       var city;
    //       city = wx.getStorageSync('city');
    //       var paramsPubNote = {
    //         city: city
    //       };
    //       note.getPubNoteInit((data) => {
    //         console.log("data", data.noteinfo)
    //         if (data.noteinfo && data.noteinfo.id) {
    //           wx.redirectTo({
    //             url: '/pages/findjob/index'
    //           })
    //         } else {
    //           wx.navigateTo({
    //             url: "/pages/mynote/index"
    //           })
    //         }
    //       }, paramsPubNote)
    //     } else {
    //
    //       wx.navigateTo({
    //         url: "/pages/register/index"
    //       })
    //
    //     }
    //   }, params)
    // )
    /*
        wx.navigateTo({
          url: "/pages/taskjob/index"
        })
          */
  },


  toJobDetail: function (e) {
    var id = e.currentTarget.dataset.id;

    wx.navigateTo({
      url: "/pages/jobdetail/index?id=" + id
    })

  },
  toFindworker: function (e) {


    var that = this;
    wx.switchTab({
      url: "/pages/findworker/index"
    })

  },

  toCompanydetial: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/companydetail/index?id=" + id
    })
  },


  toLogin: function (e) {


    var that = this;

    var params = {};

    token.verify(

      user.checkBind((data) => {

        if (data.isbind) {
          var ctoken = wx.getStorageSync('ctoken');

          if (ctoken) {
            var params = {
              ctoken: ctoken
            };

            company.checkLogin((data) => {

              if (data.error == 0) {
                wx.navigateTo({
                  url: "/pages/companycenter/index"
                })

              } else {
                wx.navigateTo({
                  url: "/pages/companylogin/index"
                })

              }


            }, params);




          } else {

            wx.navigateTo({
              url: "/pages/companylogin/index"
            })

          }


          /*
        var companyid = wx.getStorageSync('companyid');
        if (companyid > 0) {
          wx.navigateTo({
            url: "/pages/companycenter/index"
          })



        } else {

          wx.navigateTo({
            url: "/pages/companylogin/index"
          })
        }

        */

        } else {

          wx.navigateTo({
            url: "/pages/register/index"
          })

        }



      }, params)

    )




  },

  toArticle: function (e) {

    var that = this;


    wx.navigateTo({
      url: "/pages/article/index"
    })


    /*

    */
  },
  toLiveOn: function (e) {
    var id = e.detail.value.innerurl;
    let roomId = [id];
    let customParams = encodeURIComponent(JSON.stringify({
      path: 'pages/index/index',
      pid: 1
    }))
    wx.navigateTo({
      url: `plugin-private://APPID/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
    })
  },

  toActive: function (e) {

    var that = this;


    wx.navigateTo({
      url: "/pages/active/index"
    })




  },

  toArticleDetail: function (e) {

    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/articledetail/index?id=" + id
    })

  },

  /*下拉刷新页面*/
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    this.onShow();
  },

  checkTriggerVisibility() {
    wx.createSelectorQuery()
      .select('#triggerView')
      .boundingClientRect(rect => {
        if (!rect) return;

        // 页面滚动条顶部到 triggerView 顶部的距离是否小于 0
        const isOutOfViewport = rect.top <= 0;
        console.log("isOutOfViewport", isOutOfViewport)
        this.setData({
          showHeader: isOutOfViewport
        });
      })
      .exec();
  },

  //分享效果
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.title,
      path: '/pages/index/index'
    }
  }

})
